<!DOCTYPE html>
<html>
<body>
<script src="../resources/testharness.js"></script>
<script src="../resources/testharnessreport.js"></script>
<script src="../resources/visibility.js"></script>
<script>
'use strict';

promise_test(async t => {
  await internals.setPermission({name: 'screen-wake-lock'}, 'granted',
                                location.origin, location.origin);

  await setMainWindowHidden(true);
  
  assert_true(document.hidden);
  return promise_rejects_dom(t, "NotAllowedError", navigator.wakeLock.request('screen'));
}, "navigator.wakeLock.request('screen') fails when the document is hidden");

promise_test(async t => {
  await internals.setPermission({name: 'screen-wake-lock'}, 'granted',
                                location.origin, location.origin);

  await setMainWindowHidden(false);

  const screenLock1 = await navigator.wakeLock.request('screen');
  const screenLock2 = await navigator.wakeLock.request('screen');

  assert_false(screenLock1.released);
  assert_false(screenLock2.released);

  const wait1 = new EventWatcher(t, screenLock1, 'release').wait_for('release');
  const wait2 = new EventWatcher(t, screenLock2, 'release').wait_for('release');

  await setMainWindowHidden(true);

  await Promise.all([wait1, wait2]);

  assert_true(screenLock1.released);
  assert_true(screenLock2.released);
}, "Screen wake locks are released when the document the page is hidden");
</script>
</body>
</html>
